/**
 * AI分析面板组件
 * 显示文本分析结果和统计信息
 */

import React, { useState, useEffect } from 'react'
import { useAIAnalysis, AnalysisType, AnalysisResult } from '../../hooks/ai'
import { Button } from '../ui/Button'
import {
  Brain,
  FileText,
  TrendingUp,
  Search,
  CheckCircle,
  AlertCircle,
  Info,
  ChevronDown,
  ChevronRight,
  Loader2
} from 'lucide-react'

interface AIAnalysisPanelProps {
  text: string
  className?: string
  onAnalysisUpdate?: (result: AnalysisResult) => void
}

interface AnalysisItem {
  type: AnalysisType
  label: string
  icon: React.ComponentType<any>
  description: string
  color: string
}

export const AIAnalysisPanel: React.FC<AIAnalysisPanelProps> = ({
  text,
  className = '',
  onAnalysisUpdate,
}) => {
  const [selectedAnalyses, setSelectedAnalyses] = useState<AnalysisType[]>(['readability', 'style', 'grammar'])
  const [expandedResults, setExpandedResults] = useState<string[]>([])
  const [autoAnalyze, setAutoAnalyze] = useState(false)

  const {
    analyzeText,
    analyzeBatch,
    isAnalyzing,
    result,
    error,
    reset,
    analyzeSentiment,
    analyzeReadability,
    analyzeStyle,
    analyzeStructure,
    checkGrammar,
    analyzeSEO,
    extractKeywords,
    generateSummary,
  } = useAIAnalysis()

  const analysisOptions: AnalysisItem[] = [
    {
      type: 'readability',
      label: '可读性',
      icon: FileText,
      description: '分析文本的阅读难度和理解门槛',
      color: 'text-blue-600',
    },
    {
      type: 'style',
      label: '写作风格',
      icon: Brain,
      description: '分析写作风格和语言特征',
      color: 'text-purple-600',
    },
    {
      type: 'grammar',
      label: '语法检查',
      icon: CheckCircle,
      description: '检查语法错误和表达准确性',
      color: 'text-green-600',
    },
    {
      type: 'sentiment',
      label: '情感分析',
      icon: TrendingUp,
      description: '分析文本的情感倾向和语调',
      color: 'text-orange-600',
    },
    {
      type: 'structure',
      label: '结构分析',
      icon: Info,
      description: '评估文档结构和逻辑流程',
      color: 'text-indigo-600',
    },
    {
      type: 'seo',
      label: 'SEO分析',
      icon: Search,
      description: '分析搜索引擎优化程度',
      color: 'text-red-600',
    },
    {
      type: 'keywords',
      label: '关键词',
      icon: AlertCircle,
      description: '提取核心关键词和概念',
      color: 'text-yellow-600',
    },
    {
      type: 'summarization',
      label: '内容摘要',
      icon: FileText,
      description: '生成文本摘要和要点',
      color: 'text-teal-600',
    },
  ]

  // 自动分析
  useEffect(() => {
    if (autoAnalyze && text.length > 50 && !isAnalyzing) {
      const timer = setTimeout(() => {
        handleBatchAnalyze()
      }, 1000)
      return () => clearTimeout(timer)
    }
  }, [text, autoAnalyze, selectedAnalyses, isAnalyzing])

  // 批量分析
  const handleBatchAnalyze = async () => {
    if (selectedAnalyses.length === 0) return

    const analyses = selectedAnalyses.map(type => ({
      text,
      type,
      options: { detailLevel: 'detailed' as const }
    }))

    const results = await analyzeBatch(analyses)
    onAnalysisUpdate?.(results[Object.keys(results)[0]] || null)
  }

  // 单项分析
  const handleAnalyze = async (type: AnalysisType) => {
    const result = await analyzeText(text, type, { detailLevel: 'detailed' })
    onAnalysisUpdate?.(result)
  }

  // 切换分析项选择
  const toggleAnalysis = (type: AnalysisType) => {
    setSelectedAnalyses(prev =>
      prev.includes(type)
        ? prev.filter(t => t !== type)
        : [...prev, type]
    )
  }

  // 切换结果展开状态
  const toggleResultExpanded = (type: AnalysisType) => {
    setExpandedResults(prev =>
      prev.includes(type)
        ? prev.filter(t => t !== type)
        : [...prev, type]
    )
  }

  // 获取评分颜色
  const getScoreColor = (score: number): string => {
    if (score >= 8) return 'text-green-600'
    if (score >= 6) return 'text-yellow-600'
    if (score >= 4) return 'text-orange-600'
    return 'text-red-600'
  }

  // 渲染分析结果
  const renderAnalysisResult = (type: AnalysisType, result: AnalysisResult) => {
    const isExpanded = expandedResults.includes(type)
    const Icon = analysisOptions.find(a => a.type === type)?.icon || FileText

    return (
      <div key={type} className="border border-gray-200 rounded-lg p-4">
        <div
          className="flex items-center justify-between cursor-pointer"
          onClick={() => toggleResultExpanded(type)}
        >
          <div className="flex items-center space-x-2">
            <Icon className={`h-5 w-5 ${analysisOptions.find(a => a.type === type)?.color}`} />
            <span className="font-medium">{analysisOptions.find(a => a.type === type)?.label}</span>
            <div className="flex items-center space-x-1">
              <span className="text-sm text-gray-500">评分:</span>
              <span className={`font-bold ${getScoreColor(result.score)}`}>
                {result.score.toFixed(1)}/10
              </span>
            </div>
          </div>
          {isExpanded ? (
            <ChevronDown className="h-4 w-4 text-gray-400" />
          ) : (
            <ChevronRight className="h-4 w-4 text-gray-400" />
          )}
        </div>

        {isExpanded && (
          <div className="mt-4 space-y-3">
            {/* 摘要 */}
            {result.summary && (
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-1">分析摘要</h4>
                <p className="text-sm text-gray-600">{result.summary}</p>
              </div>
            )}

            {/* 详细信息 */}
            {result.details && Object.keys(result.details).length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2">详细信息</h4>
                <div className="bg-gray-50 rounded p-3">
                  {Object.entries(result.details).map(([key, value]) => (
                    <div key={key} className="flex justify-between py-1">
                      <span className="text-sm text-gray-600 capitalize">{key}:</span>
                      <span className="text-sm font-medium">{String(value)}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* 指标 */}
            {result.metrics && Object.keys(result.metrics).length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2">关键指标</h4>
                <div className="grid grid-cols-2 gap-2">
                  {Object.entries(result.metrics).map(([key, value]) => (
                    <div key={key} className="bg-blue-50 rounded p-2">
                      <div className="text-xs text-gray-600 capitalize">{key}</div>
                      <div className="text-sm font-bold text-blue-600">{String(value)}</div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* 建议 */}
            {result.suggestions && result.suggestions.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2">改进建议</h4>
                <ul className="space-y-1">
                  {result.suggestions.map((suggestion, index) => (
                    <li key={index} className="flex items-start space-x-2 text-sm">
                      <CheckCircle className="h-4 w-4 text-green-500 mt-0.5 flex-shrink-0" />
                      <span className="text-gray-600">{suggestion}</span>
                    </li>
                  ))}
                </ul>
              </div>
            )}

            <div className="text-xs text-gray-500 pt-2">
              执行时间: {result.executionTime}ms
            </div>
          </div>
        )}
      </div>
    )
  }

  return (
    <div className={`ai-analysis-panel bg-white border border-gray-200 rounded-lg shadow-sm ${className}`}>
      {/* 头部 */}
      <div className="border-b border-gray-200 p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <Brain className="h-5 w-5 text-blue-500" />
            <h3 className="font-medium">AI智能分析</h3>
            <span className="text-sm text-gray-500">
              ({text.length} 字符)
            </span>
          </div>

          <div className="flex items-center space-x-2">
            <label className="flex items-center space-x-1 text-sm">
              <input
                type="checkbox"
                checked={autoAnalyze}
                onChange={(e) => setAutoAnalyze(e.target.checked)}
                className="rounded"
              />
              <span>自动分析</span>
            </label>

            <Button
              variant="outline"
              size="sm"
              onClick={handleBatchAnalyze}
              disabled={selectedAnalyses.length === 0 || isAnalyzing}
            >
              {isAnalyzing ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin mr-1" />
                  分析中...
                </>
              ) : (
                '开始分析'
              )}
            </Button>

            <Button
              variant="ghost"
              size="sm"
              onClick={reset}
            >
              重置
            </Button>
          </div>
        </div>
      </div>

      {/* 分析选项 */}
      <div className="border-b border-gray-200 p-4">
        <h4 className="text-sm font-medium text-gray-700 mb-3">选择分析项目</h4>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          {analysisOptions.map((option) => {
            const Icon = option.icon
            const isSelected = selectedAnalyses.includes(option.type)

            return (
              <label
                key={option.type}
                className={`flex items-center space-x-2 p-2 rounded border cursor-pointer transition-colors ${
                  isSelected
                    ? 'border-blue-500 bg-blue-50'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
              >
                <input
                  type="checkbox"
                  checked={isSelected}
                  onChange={() => toggleAnalysis(option.type)}
                  className="rounded"
                />
                <Icon className={`h-4 w-4 ${option.color}`} />
                <span className="text-sm">{option.label}</span>
              </label>
            )
          })}
        </div>
      </div>

      {/* 错误状态 */}
      {error && (
        <div className="p-4 bg-red-50 border-b border-red-200">
          <div className="flex items-center space-x-2 text-red-700">
            <AlertCircle className="h-5 w-5" />
            <span className="text-sm">{error}</span>
          </div>
        </div>
      )}

      {/* 分析结果 */}
      <div className="p-4">
        {result ? (
          renderAnalysisResult('custom', result)
        ) : (
          <div className="text-center py-8 text-gray-500">
            <Brain className="h-12 w-12 mx-auto mb-3 text-gray-300" />
            <p>选择分析项目并点击"开始分析"来获取AI智能分析结果</p>
          </div>
        )}
      </div>
    </div>
  )
}